package net.itbaiyang.pattern.component;


import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.itbaiyang.pattern.config.SmsConfig;
import net.itbaiyang.pattern.util.CommonUtil;
import net.itbaiyang.pattern.util.JsonData;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class SmsComponent {

    @Value("${smstext.path}")
    private String URL_TEMPLATE;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    /**
     * 阿里云发送短信组件
     * @param to
     * @param value
     * @return
     */
    public JsonData aliSendCode(String to, String value){

        long beginTime = CommonUtil.getCurrentTimestamp();

        String param = "**code**:"+value+",**minute**:10";
        String url = String.format(URL_TEMPLATE,to,param,smsConfig.getSmsSignId(),smsConfig.getTemplateId());
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + smsConfig.getAppCode());
        Map<String, String> bodys = new HashMap<String, String>();
        HttpEntity<Map<String, String>> entity = new HttpEntity<>(bodys,headers);

        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
        long endTime = CommonUtil.getCurrentTimestamp();
        log.info("url={},body={}", endTime-beginTime,url, response.getBody());
        if (response.getStatusCode().is2xxSuccessful()){
            log.info("发送短信成功,响应信息:{}", response.getBody());
            return JsonData.buildCodeAndMsg(1,response.getBody());
        }else {
            log.error("发送短信失败,响应信息:{}",response.getBody());
            return JsonData.buildCodeAndMsg(-1,response.getBody());
        }
    }

}
